/**
 * Created by Demon-pro on 2015/7/26.
 */
var Page = function () {

    var $currentRow;
    var template_1 = '<tr data-flag="管段"><td><a href="javascript:;" class="btn red removeable"><i class="fa fa-minus"></i></a></td><td class="editable">管段</td><td><select><option value="null">请选择类型</option><option value="straight">直管型</option><option value="inner-support">内撑</option></select></td><td><input class="form-control input-xsmall" type="text"></td><td><input class="form-control input-xsmall" type="text"></td><td><input type="checkbox"></td><td><input type="checkbox"></td><td><input class="form-control input-xsmall" type="text"></td><td colspan="2"></td></tr>';
    var template_2 = '<tr data-flag="零件"><td><a href="javascript:;" class="btn red removeable"><i class="fa fa-minus"></i></a></td><td class="editable">零件</td><td><select><option value="null">请选择类型</option><option value="bend">弯头</option><option value="threeLinks">三通</option><option value="transition">变径</option><option value="header">联箱</option></select></td><td><input class="form-control input-xsmall" type="text"></td><td><input class="form-control input-xsmall" type="text"></td><td><input type="checkbox"></td><td><input type="checkbox"></td><td><input class="form-control input-xsmall" type="text"></td><td colspan="2"></td></tr>';
    var template_3 = '<tr data-flag="部件"><td><a href="javascript:;" class="btn red removeable"><i class="fa fa-minus"></i></a></td><td class="editable">部件</td><td><select><option value="null">请选择类型</option><option value="airdoor">风门</option><option value="sinkhole">缩孔</option><option value="other">其他</option></select></td><td><input class="form-control input-xsmall" type="text"></td><td><input class="form-control input-xsmall" type="text"></td><td><input type="checkbox"></td><td><input type="checkbox"></td><td><input class="form-control input-xsmall" type="text"></td><td colspan="2"></td></tr>';
    var template_4 = '<tr data-flag="设备"><td><a href="javascript:;" class="btn red removeable"><i class="fa fa-minus"></i></a></td><td class="editable">设备</td><td></td><td><input class="form-control input-xsmall" type="text"></td><td><input class="form-control input-xsmall" type="text"></td><td><input type="checkbox"></td><td><input type="checkbox"></td><td><input class="form-control input-xsmall" type="text"></td><td colspan="2"></td></tr>';
    var template_5 = '<tr data-flag="其他"><td><a href="javascript:;" class="btn red removeable"><i class="fa fa-minus"></i></a></td><td class="editable">提升压头损失</td><td></td><td><input class="form-control input-xsmall" type="text"></td><td><input class="form-control input-xsmall" type="text"></td><td><input type="checkbox"></td><td><input type="checkbox"></td><td><input class="form-control input-xsmall" type="text"></td><td colspan="2"></td></tr>';


    function initGlobalStyle() {
        $("table", ".form-body")
            .find("tbody")
            .find("td").attr({align: "center", valign: "middle"});
    }

    function initNewTr($tr, attributes) {
        //样式
        $tr.find("td").attr({align: "center", valign: "middle"});
        //二级标识
        $tr.attr("data-smallType", attributes.smallType);
        //标题
        $tr.find(".editable").text(attributes.title);
        //checkbox样式
        $tr.find(":checkbox").uniform();
        return $tr;
    }

    function getNewTr($context, typeName) {
        var largeType = $context.closest("table").attr("largeType");
        var index = $context.closest("tbody").children("tr[data-flag=" + typeName + "]").size() + 1;
        var title = typeName + index;
        var returnStr;
        var smallType;
        switch (typeName) {
            case "管段":
                returnStr = initNewTr($(template_1), {smallType: 1, title: title});
                smallType = 1;
                break;
            case "零件":
                returnStr = initNewTr($(template_2), {smallType: 2, title: title});
                smallType = 2;
                break;
            case "部件":
                returnStr = initNewTr($(template_3), {smallType: 3, title: title});
                smallType = 3;
                break;
            case "设备":
                returnStr = initNewTr($(template_4), {smallType: 4, title: title});
                smallType = 4;
                break;
            case "其他":
                title = $.trim($context.closest("tr").find(".editable").text()) + index;
                returnStr = initNewTr($(template_5), {smallType: 5, title: title});
                smallType = 5;
                break;
            default:
                break;
        }
        $.ajax({
            url: basePath + "suction/calculate/add",
            type: "post",
            dataType: "json",
            data: {
                lagreType: largeType,
                smallType: smallType,
                classA: "btn red removeable",
                classI: "fa fa-minus",
                title: title
            },
            success: function (data) {
                switch (smallType) {
                    case 1:
                        $context.closest("table").find("tr[data-flag='管段']").last().attr("id", data);
                        break;
                    case 2:
                        $context.closest("table").find("tr[data-flag='零件']").last().attr("id", data);
                        break;
                    case 3:
                        $context.closest("table").find("tr[data-flag='部件']").last().attr("id", data);
                        break;
                    case 4:
                        $context.closest("table").find("tr[data-flag='设备']").last().attr("id", data);
                        break;
                    case 5:
                        $context.closest("table").find("tr[data-flag='其他']").last().attr("id", data);
                        break;
                }
                toast.success();
            }
        });
        return returnStr;
    }

    function editHandle() {
        var old = "";
        //启用编辑
        $(document.body).on("dblclick", ".editable", function () {
            old = $.trim($(this).text());
            $(this).empty().append($("<input class='form-control input-small' type='text'>").val(old));
            $(this).children("input").focus();
        });

        //保存编辑数据
        $(document.body).on("blur", ".editable", function () {
            var text = $.trim($(this).children("input").val());
            $(this).empty();
            if (text == "") {
                $(this).text(old);
            } else {
                $.ajax({
                    url: basePath + "suction/calculate/editTitle",
                    type: "post",
                    dataType: "json",
                    data: {
                        id: $(this).closest("tr").attr("id"),
                        title: text
                    },
                    success: function () {
                        toast.success();
                    }
                });
                $(this).text(text);
            }
        });
    }

    function addHandle() {
        $(document.body).on("click", ".addable", function () {
            var typeName = $(this).closest("tr").attr("data-flag");
            var $newTr = getNewTr($(this), typeName);
            $(this).closest("tbody").children("tr[data-flag=" + typeName + "]:last").after($newTr);
        });

    }

    function removeHandle() {
        $(document.body).on("click", ".removeable", function () {
            $currentRow = $(this).closest("tr");
            var parentTable = $currentRow.closest("table");
            var flag = $currentRow.data("flag");
            $.ajax({
                url: basePath + "suction/calculate/del?id=" + $currentRow.attr("id"),
                type: "DELETE",
                dataType: "json",
                success: function () {
                    toast.success();
                    $currentRow.remove();
                    autoCalSum(parentTable,flag);
                }
            });
        })
    }

    function hideHandle() {
        $(document.body).on("click", ".hideable", function () {
            var flag = $(this).attr("data-flag");
            if ($(this).hasClass("yellow")) {
                $(this).closest("tr").siblings("tr[data-flag=" + flag + "]").hide();
                $(this).removeClass("yellow").addClass("blue").children("i").removeClass("fa-angle-up").addClass("fa-angle-down");
            } else {
                $(this).closest("tr").siblings("tr[data-flag=" + flag + "]").show();
                $(this).removeClass("blue").addClass("yellow").children("i").removeClass("fa-angle-down").addClass("fa-angle-up")
            }
        })
    }

    var getRowValues = function () {
        return {
            id: $currentRow.attr("id"),
            lagreType: $currentRow.closest("table").attr("largeType"),
            smallType: $currentRow.attr("data-smallType"),
            type: $(":selected", $currentRow).val(),
            check1: $(":checkbox:eq(0)", $currentRow).prop("checked"),
            check2: $(":checkbox:eq(1)", $currentRow).prop("checked"),
            z: validate.isNumber($(":text:eq(0)", $currentRow).val()) ? $(":text:eq(0)", $currentRow).val() : 0,
            p: validate.isNumber($(":text:eq(1)", $currentRow).val()) ? $(":text:eq(1)", $currentRow).val() : 0,
            lost: validate.isNumber($(":text:eq(2)", $currentRow).val()) ? $(":text:eq(2)", $currentRow).val() : 0
        }
    };

    var saveRow = function () {
        $.ajax({
            url: basePath + "suction/calculate/saveRow",
            type: "POST",
            dataType: "json",
            data: getRowValues()
        });
    };

    var autoCalSum = function ($parentTable,flag) {
        var rows = [];
        $parentTable.find($("tr[data-flag=" + flag + "]")).each(function () {
            $currentRow = $(this);
            rows.push(getRowValues());
        });
        $.ajax({
            url: basePath + "suction/calculate/autoCalRowSum",
            data: JSON.stringify(rows),
            dataType: "json",
            contentType: "application/json;charset=utf8",
            type: "post",
            success: function (data) {
                if (data == null) {
                    toast.error("您之前的填写的信息不完整!<br>计算点阻力损失和设计点阻力损失无法计算!");
                    return;
                }
                var $titleTr = $parentTable.find("tr[data-flag=" + flag + "]:eq(0)").prev();
                $titleTr.find(".calculateLost").val(data.calculateLost);
                $titleTr.find(".designLost").val(data.designLost);
                autoCalTableTotal($parentTable);
            }
        })
    };

    var autoCalTableTotal = function ($parentTable) {
        var $titleTrs = $parentTable.find(".title");
        var smallTypeTotal = [];
        var calculateLost = 0;
        var designLost = 0;
        $titleTrs.each(function () {
            calculateLost = $(this).find(".calculateLost").val();
            designLost = $(this).find(".designLost").val();
            smallTypeTotal.push({
                calculateLost: calculateLost == "" ? "0.0" : calculateLost,
                designLost: designLost == "" ? "0.0" : designLost
            })
        });
        $.ajax({
            url: basePath + "suction/calculate/autoCalTableTotal",
            dataType: "json",
            type: "post",
            data: JSON.stringify({
                source: $parentTable.attr("largeType"),
                data: smallTypeTotal
            }),
            contentType: "application/json;charset=utf8",
            success: function (data) {
                $(":text[readonly]", $parentTable).autoInject({
                    mode: "id",
                    data: data
                })
            }
        })
    };


    var selectHandle = function () {
        //监听option选择
        $(document.body).on("click", "option", function () {
            var val = $(this).val();
            $currentRow = $(this).closest("tr");
            saveRow();
            if (val == "null" || val == "other")
                return;
            $("#toolbarIframe", "#modalDialog").attr("src", basePath + "toolbar/" + val + '?id='+ $currentRow.attr("id"));

            $("#modalDialog").modal("show");
        });
    };

    //手动输入改变值
    var tableInputHandle = function () {
        $("table").on("blur", ":text:not([readonly])", function () {
            validate.init($(this));
            if (validate.isNotNumber($(this).val())) {
                validate.invalid();
            } else {
                $currentRow = $(this).closest("tr");
                if ($currentRow.find(":text").index($(this)) == 2){
                    saveRow();
                    autoCalSum($currentRow.closest("table"), $currentRow.data("flag"));
                }else {
                    $.ajax({
                        url: basePath + "suction/calculate/autoCal",
                        type: "post",
                        dataType: "json",
                        data: getRowValues(),
                        success: function (data) {
                            $("input:text:eq(2)", $currentRow).val(data);
                            saveRow();
                            autoCalSum($currentRow.closest("table"), $currentRow.data("flag"));
                        }
                    });
                }
                validate.valid();
            }
        })
    };

    //改变checkbox值
    var tableCheckBoxHandle = function () {
        $("table").on("click.save", ":checkbox", function () {
            $currentRow = $(this).closest("tr");
            saveRow();
            autoCalSum($currentRow.closest("table"),$currentRow.data("flag"));
        })
    };

    //modal改变值
    var buttonHandle = function () {
        $("#getToolBarValues").on('click', function () {
            $.post(basePath + "suction/calculate/getToolBarValues?id=" + $currentRow.attr("id"), function (data) {
                $currentRow.find("input:text").eq(0).val(data.z);
                $currentRow.find("input:text").eq(1).val(data.p);
                $currentRow.find("input:text").eq(2).val(data.lost);
                $("#modalDialog").modal('hide');
                saveRow();
                autoCalSum($currentRow.closest("table"),$currentRow.data("flag"));
            });
        });

        $("#quit").on('click', function () {
            $.get(basePath + "suction/calculate/setE", function () {
            })
        })
    };

    var paramHandle = function (){
      $("#E10,#E22").blur(function (){
          validate.init($(this));
          if (validate.isNotNumber($(this).val())){
              validate.invalid();
              return;
          }
          $.ajax({
              url:basePath + "suction/calculate/updateParam",
              dataType:"json",
              type:"post",
              data:{
                  paramName:$(this).attr("id"),
                  paramValue:$(this).val()
              },
              success:function (){
                  validate.valid();
              }
          })
      })
    };

    var paramInit = function() {
        $.post(basePath + "suction/calculate/getParamInit",function() {});
    };

    return {
        init: function () {
            paramInit();
            editHandle();
            hideHandle();
            addHandle();
            removeHandle();
            initGlobalStyle();
            selectHandle();
            buttonHandle();
            tableInputHandle();
            tableCheckBoxHandle();
            paramHandle();
        }
    }
}();
